package com.sxbbc.plat.controller.jz;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.rest.RestFactory;
import com.sxbbc.common.basics.utils.encrypts.des.DESEncode;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.SysLogs;
import com.sxbbc.common.core.entity.jz.SysMenus;
import com.sxbbc.common.core.entity.jz.SysRoles;
import com.sxbbc.common.core.entity.jz.SysUser;
import com.sxbbc.common.core.service.ISysLogsService;
import com.sxbbc.common.core.service.ISysRolesService;
import com.sxbbc.common.core.service.ISysUserService;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.plat.common.MappingUtils;
import com.sxbbc.plat.util.PlatSession;
import com.sxbbc.plat.util.SystemLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author leehao
 * 角色管理/操作员管理/系统日志
 * 统一放在该控制层，视图层命名为/base/...
 * @date 2019-04-27 09:59
 */
@Controller
public class BaseController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRolesService sysRolesService;
    @Autowired
    private ISysLogsService sysLogsService;

    /**
     * 操作员列表页面
     *
     * @param page
     * @param sysUser
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @GetMapping(value = MappingUtils.SHOW_USER_LIST)
    public ModelAndView showUsersList(HttpServletRequest request, BasePage<SysUser> page, SysUser sysUser) {
        BasePage<SysUser> userPage = sysUserService.queryList(page, sysUser);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_USER_LIST);
        view.addObject("pageInfo", userPage);
        return view;
    }

    /**
     * 新增/编辑操作员
     *
     * @param imgUrl 头像url
     * @param user   sysUser对象
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @SystemLog(methods = "新增编辑管理员", module = "用户管理")
    @RequestMapping(value = MappingUtils.EDIT_USER)
    @ResponseBody
    public RestResponse editUser(@RequestParam(name = "imgUrl", required = false) MultipartFile imgUrl,
                                 SysUser user, HttpServletRequest request) {
        if (user.getId() == null && StringUtils.isBlank(user.getLogin())) {
            return GetRest.getFail("请输入登录名");
        }
        if (StringUtils.isBlank(user.getName())) {
            return GetRest.getFail("请输入管理员姓名");
        }
        if (StringUtils.isBlank(user.getPhone())) {
            return GetRest.getFail("请输入管理员联系电话");
        }
        /*if (user.getId() == null && imgUrl == null) {
            return GetRest.getFail("请上传管理员头像");
        }*/
        if (user.getRoleid() == null) {
            return GetRest.getFail("请选择管理员所属角色");
        }
        if (user.getId() == null) {
            SysUser sysUser = sysUserService.selectByLogin(user.getLogin());
            if (sysUser != null) {
                return GetRest.getFail("该登录名已存在");
            }
        }
        // 头像上传
        /*RestUploadFileInfo result = UploadUtils.getInstance().uploadFile(imgUrl);
        if (result.isStatus()) {
            user.setHeadurl(result.getData());
        }else if(!result.isStatus() && imgUrl != null){
            return GetRest.getFail("图片上传失败：" + result.getDesc());
        }*/
        // 保存加密后的默认密码
        user.setPassword(DESEncode.getInstance().encrypt(StaticUtils.DEFAULT_PASSWORD));
        // 新增/编辑
        boolean save = sysUserService.saveOrUpdate(user);
        if (!save) {
            throw new ThrowJsonException("保存管理员失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    /**
     * 新增/编辑操作员页面
     *
     * @param id 操作员id（为空时新增）
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @GetMapping(value = MappingUtils.SHOW_USER_EDIT)
    public ModelAndView showUserEdit(Integer id, HttpServletRequest request) {
        SysUser sysUser = sysUserService.getById(id);
        List<SysRoles> list = sysRolesService.list(null);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_USER_EDIT);
        view.addObject("user", sysUser);
        view.addObject("roles", list);
        return view;
    }

    @RequestMapping(value = MappingUtils.HANDLE_USER_STATUS)
    @ResponseBody
    @SystemLog(methods = "启用/禁用操作员", module = "系统管理")
    public RestResponse handleUserStatus(Integer id, Integer status) {
        return sysUserService.handleUserStatus(id, status);
    }

    @RequestMapping(value = MappingUtils.DELETE_USER)
    @ResponseBody
    @SystemLog(methods = "删除操作员", module = "系统管理")
    public boolean deleteUser(Integer id) {
        return sysUserService.removeById(id);
    }

    /**
     * 角色列表页面
     *
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @GetMapping(value = MappingUtils.SHOW_ROLE_LIST)
    public ModelAndView showRolesList(HttpServletRequest request) {
        List<SysRoles> list = sysRolesService.list(null);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_ROLE_LIST);
        view.addObject("list", list);
        return view;
    }

    /**
     * 查询角色列表
     *
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @GetMapping(value = MappingUtils.SELECT_ROLE_LIST)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse selectRolesList(BasePage<SysRoles> page) {
        sysRolesService.page(page);
        return RestFactory.success(page.getRecords(), page.getTotal());
    }

    /**
     * 新增/编辑角色页面
     *
     * @param id 角色id
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.SHOW_ROLE_EDIT)
    public ModelAndView showRoleEdit(Integer id, HttpServletRequest request) {
        SysRoles role = sysRolesService.getById(id);
        List<SysMenus> list = sysRolesService.queryMenusByRoleId(id);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_ROLE_EDIT);
        view.addObject("role", role);
        view.addObject("list", list);
        view.addObject("id", id);
        return view;
    }

    /**
     * 新增/编辑角色
     *
     * @param role sysRoles对象
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.EDIT_ROLE)
    @ResponseBody
    @SystemLog(methods = "新增编辑角色", module = "用户管理")
    public RestResponse editRole(SysRoles role, HttpServletRequest request) {
        if (StringUtils.isBlank(role.getName())) {
            return GetRest.getFail("请填写角色名称");
        }
        if (StringUtils.isBlank(role.getMenuIds())) {
            return GetRest.getFail("请选择菜单");
        }
        //去重复
        Set<String> menuList = new HashSet<>(Arrays.asList(role.getMenuIds().split(",")));
        String menuss = StringUtils.join(menuList.toArray(), ",");
        role.setMenuIds(menuss);
        boolean b = sysRolesService.saveOrUpdate(role);
        if (!b) {
            throw new ThrowJsonException("保存角色信息出错");
        }
        return GetRest.getSuccess("操作成功");
    }

    /**
     * 启用/禁用角色
     *
     * @param id     角色id
     * @param status 状态，0禁用，1启用
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.HANDLE_ROLE_STATUS)
    @ResponseBody
    @SystemLog(methods = "启用/禁用角色", module = "系统管理")
    public RestResponse handleRoleStatus(Integer id, Integer status) {
        return sysRolesService.handleRoleStatus(id, status);
    }

    /**
     * 删除角色信息
     *
     * @param id 角色id
     * @return 成功true，反之false
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.DELETE_ROLE)
    @ResponseBody
    @SystemLog(methods = "删除角色信息", module = "系统管理")
    public boolean deleteRole(Integer id) {
        return sysRolesService.removeById(id);
    }

    /**
     * 日志列表
     *
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.SHOW_LOGS_LIST)
    public ModelAndView showLogsList() {
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_LOGS_LIST);
        return view;
    }

    /**
     * 查询日志列表
     *
     * @param basePage 分页数据
     * @param log      查询数据
     * @return 分页数据
     * @author xiaoky
     */
    @RequestMapping(value = MappingUtils.QUERY_LOGS_LIST)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryLogsList(BasePage<SysLogs> basePage, SysLogs log) {
        Page<SysLogs> pageInfo = sysLogsService.queryLogsList(basePage, log);
        return RestFactory.success(pageInfo.getRecords(), pageInfo.getTotal());
    }

    /**
     * 显示修改密码页面
     *
     * @param request
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.SHOW_UPDATE_PASSWORD)
    public ModelAndView showUpdatePassword(HttpServletRequest request) {
        Integer userId = PlatSession.getUserId(request);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_UPDATE_PASSWORD);
        view.addObject("id", userId);
        return view;
    }

    /**
     * 修改密码方法
     *
     * @param userId    登录的用户id
     * @param oldPwd    旧密码
     * @param newPwdOne 新密码1
     * @param newPwdTwo 新密码2
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.UPDATE_PASSWORD)
    @ResponseBody
    @SystemLog(methods = "修改登录密码", module = "用户管理")
    public RestResponse updatePassword(Integer userId, String oldPwd, HttpServletRequest request,
                                       String newPwdOne, String newPwdTwo) {
        return sysUserService.updatePassword(userId, oldPwd, newPwdOne, newPwdTwo);
    }
}
